using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Pool;

/// <summary>
/// 实体管理服务 - 业务逻辑层
/// </summary>
public class EntityService : ServiceBase
{
    private EntityRepository m_EntityRepository;
    
    protected override void OnInitialize()
    {
        m_EntityRepository = new EntityRepository();
        Logger.Log("EntityService", "EntityService initialized");
    }
    
    /// <summary>
    /// 注册实体
    /// </summary>
    public void RegisterEntity(Entity entity)
    {
        if (entity == null) return;
        
        m_EntityRepository.Add(entity);
        
        // 可以添加业务逻辑，比如初始化实体状态
        InitializeEntityState(entity);
    }
    
    /// <summary>
    /// 注销实体
    /// </summary>
    public void UnregisterEntity(Entity entity)
    {
        if (entity == null) return;
        
        m_EntityRepository.Remove(entity);
        
        // 清理实体相关资源
        CleanupEntityResources(entity);
    }
    
    /// <summary>
    /// 获取所有实体 - 使用对象池
    /// </summary>
    public List<Entity> GetAllEntities()
    {
        var allEntities = m_EntityRepository.GetAll();
        var result = ListPool<Entity>.Get();
        result.AddRange(allEntities);
        return result;
    }
    
    /// <summary>
    /// 根据类型获取实体 - 使用对象池
    /// </summary>
    public List<T> GetEntitiesByType<T>() where T : Entity
    {
        var entities = m_EntityRepository.GetByType<T>();
        var result = ListPool<T>.Get();
        result.AddRange(entities);
        return result;
    }
    
    /// <summary>
    /// 根据组件获取实体 - 使用对象池
    /// </summary>
    public List<Entity> GetEntitiesByComponent<T>() where T : Component
    {
        var entities = m_EntityRepository.GetByComponent<T>();
        var result = ListPool<Entity>.Get();
        result.AddRange(entities);
        return result;
    }
    
    /// <summary>
    /// 查找最近的敌人
    /// </summary>
    public Entity FindNearestEnemy(Entity searcher, float maxDistance = float.MaxValue)
    {
        if (searcher == null) return null;
        
        var allEntities = GetAllEntities();
        Entity nearestEnemy = null;
        float nearestDistance = maxDistance;
        Vector3 searcherPos = searcher.transform.position;
        
        foreach (var entity in allEntities)
        {
            if (entity == searcher || entity.HealthComponent.IsDead) continue;
            
            // 检查是否为敌人
            if (!IsEnemy(searcher, entity)) continue;
            
            float distance = Vector3.Distance(searcherPos, entity.transform.position);
            if (distance < nearestDistance)
            {
                nearestDistance = distance;
                nearestEnemy = entity;
            }
        }
        
        return nearestEnemy;
    }
    
    /// <summary>
    /// 获取范围内的敌人 - 使用对象池
    /// </summary>
    public List<Entity> GetEnemiesInRange(Entity searcher, float range)
    {
        if (searcher == null) return ListPool<Entity>.Get();
        
        var allEntities = GetAllEntities();
        var enemies = ListPool<Entity>.Get();
        Vector3 searcherPos = searcher.transform.position;
        float rangeSquared = range * range; // 使用平方距离避免开方
        
        foreach (var entity in allEntities)
        {
            if (entity == searcher || entity.HealthComponent.IsDead) continue;
            if (!IsEnemy(searcher, entity)) continue;
            
            float distanceSquared = (entity.transform.position - searcherPos).sqrMagnitude;
            if (distanceSquared <= rangeSquared)
            {
                enemies.Add(entity);
            }
        }
        
        return enemies;
    }
    
    /// <summary>
    /// 检查两个实体是否为敌人关系
    /// </summary>
    private bool IsEnemy(Entity entity1, Entity entity2)
    {
        // 土豆地雷不应该被僵尸攻击，也不应该吸引僵尸的仇恨
        if (entity1 is PotatoMine || entity2 is PotatoMine)
        {
            return false;
        }
        
        if (entity1 is Plant && entity2 is Zombie) return true;
        if (entity1 is Zombie && entity2 is Plant) return true;
        return false;
    }
    
    /// <summary>
    /// 初始化实体状态
    /// </summary>
    private void InitializeEntityState(Entity entity)
    {
        // 业务逻辑：初始化实体状态
        Logger.Log("EntityService", $"Initializing entity state for {entity.name}");
    }
    
    /// <summary>
    /// 清理实体资源
    /// </summary>
    private void CleanupEntityResources(Entity entity)
    {
        // 业务逻辑：清理实体相关资源
        Logger.Log("EntityService", $"Cleaning up resources for {entity.name}");
    }
    
    protected override void OnDispose()
    {
        // 清理所有实体
        var allEntities = GetAllEntities();
        foreach (var entity in allEntities)
        {
            CleanupEntityResources(entity);
        }
        
        Logger.Log("EntityService", "EntityService disposed");
    }
}
